<?php

class Quad_Str {
	
	public static function utf8Convert($str, $attempt = null) {
		if (!is_array($attempt)) {
			$attempt = array("CP1252", "ISO-8859-1");
		}
		// if iconv encounters a character outside it's charset, the string is truncated.
		// therefore, if the string length is unchanged, we found the charset
		$utf8 = iconv("UTF-8", "UTF-8", $str);
		if (strlen($utf8) == strlen($str)) {
			// string must already be utf8
			return $utf8;
		}
		foreach ($attempt as $charset) {
			$converted = iconv($charset, $charset, $str);
			if (strlen($converted) == strlen($str)) {
				// string must be that charset; convert it
				return iconv($charset, "UTF-8//TRANSLIT//IGNORE", $str);
			}
		}
		// other charset; convert and strip out unknown chars
		return iconv("UTF-8", "UTF-8//TRANSLIT//IGNORE", $str);
	}
	
	// FROM drupal_validate_utf8
	public static function isUtf8($str) {
	  if (strlen($str) == 0) {
	    return true;
	  }
	  return (preg_match('/^./us', $str) == 1);
	}
	
	// beginsWith
	// endsWith
	
}